package com.example.liang.basamovie.json;

import android.util.Log;

import com.example.liang.basamovie.bean.SeleteFilmInfo;
import com.example.liang.basamovie.bean.SeleteItemBean;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * 搜索电影接口的解析类
 */
public class FindSeleteJson {
    public static List<SeleteItemBean> getList(String path){
        try {
            JSONObject object = new JSONObject(path);
            JSONArray movieList = object.getJSONArray("recommendMovieList");
            SeleteItemBean seleteItemBean;
            SeleteFilmInfo seleteFilmInfo;
            List<SeleteItemBean> lists=new ArrayList();
            for (int i = 0; i < movieList.length(); i++) {
                List<SeleteFilmInfo> list=new ArrayList<>();
                seleteItemBean=new SeleteItemBean();
                JSONObject jsonObject = movieList.getJSONObject(i);
                seleteItemBean.setTitle(jsonObject.optString("title"));
                JSONArray movieInfo = jsonObject.getJSONArray("movieInfo");
                for (int j = 0; j < movieInfo.length(); j++) {
                    seleteFilmInfo=new SeleteFilmInfo();
                    JSONObject object1 = movieInfo.getJSONObject(j);
                    seleteFilmInfo.setTitle(object1.optString("title"));
                    JSONObject posters = object1.getJSONObject("posters");
                    if(posters.has("medium")){
                        seleteFilmInfo.setImageUrl(posters.optString("medium"));
                    }else {
                        seleteFilmInfo.setImageUrl(posters.optString("small"));
                    }
                    seleteFilmInfo.setId(object1.optString("id"));
                    if(object1.has("countries")){
                        seleteFilmInfo.setCountries((String) object1.getJSONArray("countries").get(0));
                    }
                    seleteFilmInfo.setYear(object1.optString("year"));
                    list.add(seleteFilmInfo);
                }
                seleteItemBean.setList(list);
                lists.add(seleteItemBean);
            }

            Log.e("message","搜索电影的接口解析正确");
            return lists;
        } catch (JSONException e) {
            e.printStackTrace();
        }
        Log.e("message","搜索电影的接口解析出错");
        return new ArrayList<>();
    }
}
